﻿using System.Collections.Generic;

namespace Kindohm.KSynth.Library
{
    public class Synthesizer : AttenuatorBase, ISampleMaker
    {
        Envelope envelope;
        
        public Synthesizer()
        {
            this.envelope = new Envelope();
            this.envelope.Attack = 0;
            this.envelope.Sustain = uint.MaxValue;
            this.envelope.Decay = 0;
            this.Oscillators = new List<Oscillator>();
            this.PitchBend = 0;
            this.Delay = new Delay();
            this.Delay.Length = 0;
            this.Delay.Attenuation = -10;
            this.Delay.Enabled = true;
        }

        public double PitchBend { get; set; }
        public Envelope Envelope
        {
            get { return this.envelope; }
        }

        public Delay Delay { get; set; }

        public List<Oscillator> Oscillators
        {
            get;
            set;
        }

        public double Frequency
        {
            get
            {
                return this.Oscillators[0].Frequency;
            }
            set
            {
                for (int i = 0; i < this.Oscillators.Count; i++)
                    this.Oscillators[i].Frequency = value;
            }
        }

        public StereoSample GetSample()
        {

            this.Bend();
            int factor = this.Oscillators.Count;
            StereoSample finalSample = new StereoSample();
            for (int i = 0; i < this.Oscillators.Count; i++)
            {
                StereoSample oscillatorSample = this.Oscillators[i].GetSample();
                finalSample.LeftSample += (short)((int)oscillatorSample.LeftSample / factor);
                finalSample.RightSample += (short)((int)oscillatorSample.RightSample / factor);

            }
            this.envelope.ProcessSample(finalSample);
            StereoSample newSample = this.Delay.ProcessSample(finalSample);
            return newSample;
        }

        void Bend()
        {
            this.Frequency += this.PitchBend;
        }

    }
}
